package com.atguli.gulimall.product.service.impl;

import com.atguli.common.entity.QueryWrapperVO;
import com.atguli.common.enums.BizCodeEnum;
import com.atguli.common.exception.RRException;
import com.atguli.gulimall.product.service.CategoryBrandRelationService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguli.common.utils.PageUtils;
import com.atguli.common.utils.Query;

import com.atguli.gulimall.product.dao.CategoryDao;
import com.atguli.gulimall.product.entity.CategoryEntity;
import com.atguli.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("categoryService")
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Resource
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(QueryWrapperVO params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查出所有分类
     * 组装成父子的树形结构
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        //所有分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        //分装
        List<CategoryEntity> Menu1 = categoryEntities.stream()
                .filter((item) -> item.getParentCid() == 0 )
                .map(menu -> {
                    menu.setChildren(getChildren(menu,categoryEntities));
                    return menu;
                })
                .sorted((menu1,menu2) -> {
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                })
                .collect(Collectors.toList());
        return Menu1;
    }

    /**
     * 自定义批量删除方法
     *
     * @param asList
     */
    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 检查当前删除的菜单是否被别的地方引用
        final int count = baseMapper.deleteBatchIds(asList);
    }

    /**
     * 查询三级分类的完整路径
     *
     * @param catelogId
     * @return
     */
    @Override
    public Long[] findCatePath(Long catelogId) {
        log.info("进入查询三级分类的完整路径");
        List<Long> paths = new ArrayList<>();
        findParentPath(catelogId, paths);
        log.info("查询完成");
        return (Long[]) paths.toArray(new Long[paths.size()]);
    }

    /**
     * 级联更新
     *
     * @param category
     */
    @Override
    @Transactional(rollbackFor = RRException.class)
    public void updateByCascade(CategoryEntity category) {
        this.updateById(category);
        if (StringUtils.isNotEmpty(category.getName())) {
            log.info("同步更新其他关联表");
            try {
                categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
            }catch (RuntimeException e){
                log.error(e.getLocalizedMessage());
                throw new RRException(BizCodeEnum.TRANSACTIONAL_EXCEPTION.getMessage(),BizCodeEnum.TRANSACTIONAL_EXCEPTION.getCode());
            }
        }
    }

    private void findParentPath(Long catelogId,List<Long> paths) {
        log.info("进入递归查询三级分类的完整路径");
        final CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(),paths);
        }
        // 收集当前节点的id
        paths.add(catelogId);
    }

    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all){
        List<CategoryEntity> children = all.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid().equals(root.getCatId()))
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildren(categoryEntity,all));
                    return categoryEntity;
                })
                .sorted((menu1,menu2) -> {
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                })
                .collect(Collectors.toList());
        return children;
    }
}